package com.rzjm.exercise.module.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.*;
import com.rzjm.exercise.common.utils.encryp.impl.MD5Utils;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.domain.excel.AdminSysUserExcel;
import com.rzjm.exercise.module.domain.excel.CitizenExcel;
import com.rzjm.exercise.module.service.CitizenService;
import com.rzjm.exercise.module.service.TownsService;
import com.rzjm.exercise.sys.core.dict.domain.DictDO;
import com.rzjm.exercise.sys.core.dict.service.DictService;
import com.rzjm.exercise.sys.system.role.domain.RoleDO;
import com.rzjm.exercise.sys.system.role.service.RoleService;
import com.rzjm.exercise.sys.system.user.domain.SysUserTownRelation;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import com.rzjm.exercise.sys.system.user.service.SysUserTownRelationService;
import com.rzjm.exercise.sys.system.user.service.UserService;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.*;

/**
 * 居民信息
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2020-12-15 22:36:23
 */
@Controller
@RequestMapping("/module/citizen")
public class CitizenController extends BaseController {

    @Resource
    private CitizenService citizenService;
    @Resource
    private TownsService townsService;
    @Resource
    private UserService userService;
    @Resource
    private SysUserTownRelationService userTownRelationService;
    @Resource
    private DictService dictService;
    @Resource
    private RoleService roleService;

    @Value("${projecturl.uploadPath}")
    private String uploadPath;

    @Value("${projecturl.imgurl}")
    private String imgUrl;

    @Log("查询设备页面")
    @GetMapping()
    @RequiresPermissions("module:citizen:citizen")
    String citizen(Model model) {
        UserDO user = getUser();
        QueryWrapper<Towns> qw = new QueryWrapper<>();
        qw.eq("district_id", 1319);
        qw.eq("state",1);
        qw.eq("parent_id",0);
        if(user.getUserLevel() !=null && user.getUserType() == 7){
            if(user.getUserLevel() == 2 || user.getUserLevel() == 3){//镇
                qw.eq("id",user.getTownId());
            }
        }

        List<Towns> towns = townsService.list(qw);
        List<Towns> villages = new ArrayList<>();
        if(user.getUserLevel() !=null&& user.getUserLevel() == 3){
            villages = townsService.selectListByColumn("parent_id",user.getVillageId());
        }else{
            villages = townsService.selectListByColumn("parent_id",towns.get(0).getId());
        }
        model.addAttribute("towns",towns);
        model.addAttribute("villages",villages);
        model.addAttribute("user_type",user.getUserType());
        model.addAttribute("townId",user.getTownId());
        model.addAttribute("userLevel",user.getUserLevel());
        return "module/citizen/citizen";
    }

    @Log("查询设备")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("module:citizen:citizen")
    public DataTableLayUI<Citizen> list(DataTableLayUI<Citizen> condition) {
        UserDO user = getUser();
        QueryWrapper<Citizen> qw = new QueryWrapper<>();
        Map<String,Object> map = condition.getSearchParams();
        String keyword = map.containsKey("search_like_keyword")?map.get("search_like_keyword").toString():null;
        String townId = map.containsKey("search_eq_townId")?map.get("search_eq_townId").toString():null;
        String villageId = map.containsKey("search_eq_villageId")?map.get("search_eq_villageId").toString():null;
        String begin_date = map.containsKey("begin_date") ? map.get("begin_date").toString(): null;
        String end_date = map.containsKey("end_date") ? map.get("end_date").toString(): null;

        if(user.getUserLevel() !=null && user.getUserType() == 7){
            if(user.getUserLevel() == 2){//镇
//                map.put("search_eq_townId",user.getTownId());
                qw.eq("town_id",user.getTownId());
                if(StrUtil.isNotEmpty(villageId)){
                    qw.eq("village_id",villageId);
                }
            }else if(user.getUserLevel() == 3){//村
//                map.put("search_eq_villageId",user.getVillageId());
                qw.eq("village_id",user.getVillageId());
            }
        }else{
            if(StrUtil.isNotEmpty(townId)){
                qw.eq("town_id",townId);
            }
            if(StrUtil.isNotEmpty(villageId)){
                qw.eq("village_id",villageId);
            }
        }

        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            qw.between("update_time",begin_date,end_date);
        }
        if(StrUtil.isNotEmpty(keyword)){
            qw.like("holder_name",keyword);
        }
        condition.setQw(qw);
        DataTableLayUI<Citizen> dt = citizenService.pageSearchLayUI(condition);
        List<Citizen> list = dt.getData();
        list.forEach(citizen -> {
            citizen.setQrCode(imgUrl+ citizen.getQrCode());
        });
        return dt;
    }

    @Log("新增设备页面")
    @GetMapping("/add")
    @RequiresPermissions("module:citizen:add")
    String add(Model model) {
        Citizen citizen = new Citizen();
        model.addAttribute("citizen", citizen);

        UserDO user = getUser();
        QueryWrapper<Towns> qw = new QueryWrapper<>();
        qw.eq("district_id", 1319);
        qw.eq("state",1);
        qw.eq("parent_id",0);
        if(user.getUserLevel() !=null && user.getUserType() == 7){
            if(user.getUserLevel() == 2 || user.getUserLevel() == 3){//镇
                qw.eq("id",user.getTownId());
            }
        }

        List<Towns> towns = townsService.list(qw);
        List<Towns> villages = new ArrayList<>();
        if(user.getUserLevel() !=null && user.getUserLevel() == 3){
            villages = townsService.selectListByColumn("id",user.getVillageId());
        }else{
            villages = townsService.selectListByColumn("parent_id",towns.get(0).getId());
        }
        model.addAttribute("towns",towns);
        model.addAttribute("villages",villages);

        List<DictDO> room_types = dictService.listByType("room_type");
        model.addAttribute("room_types",room_types);

        List<DictDO> heating_modes = dictService.listByType("heating_mode");
        model.addAttribute("heating_modes",heating_modes);

        return "module/citizen/detail";
    }


    @Log("编辑设备页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:citizen:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        Citizen citizen = citizenService.findById(id);
        model.addAttribute("citizen", citizen);

        UserDO user = getUser();
        QueryWrapper<Towns> qw = new QueryWrapper<>();
        qw.eq("district_id", 1319);
        qw.eq("state",1);
        qw.eq("parent_id",0);

        if(user.getUserLevel() !=null && user.getUserType() == 7){
            if(user.getUserLevel() == 2 || user.getUserLevel() == 3){//镇
                qw.eq("id",user.getTownId());
            }
        }

        List<Towns> towns = townsService.list(qw);
        List<Towns> villages = townsService.selectListByColumn("parent_id",citizen.getTownId());
        if(CollUtil.isNotEmpty(villages)){
            if(user.getUserLevel() !=null && user.getUserLevel() == 3){
                villages = townsService.selectListByColumn("parent_id",user.getVillageId());
            }else{
                villages = townsService.selectListByColumn("parent_id",towns.get(0).getId());
            }
        }
        model.addAttribute("towns",towns);
        model.addAttribute("villages",villages);

        List<DictDO> room_types = dictService.listByType("room_type");
        model.addAttribute("room_types",room_types);

        List<DictDO> heating_modes = dictService.listByType("heating_mode");
        model.addAttribute("heating_modes",heating_modes);

        return "module/citizen/detail";
    }


    @Log("编辑设备页面")
    @PostMapping("/villages")
    @ResponseBody
    public R villages(Integer townId) {
        UserDO user = getUser();
        List<Towns> villages = new ArrayList<>();
        QueryWrapper<Towns> qw = new QueryWrapper<>();
        if(user.getUserLevel() !=null && user.getUserType() == 7){
            if(user.getUserLevel() == 2){//镇
                qw.eq("parent_id",user.getTownId());
            }else if(user.getUserLevel() == 3) {
                qw.eq("parent_id",user.getTownId());
                qw.eq("id",user.getVillageId());
            } else{
                qw.eq("parent_id",townId);
            }
        }else{
            qw.eq("parent_id",townId);
        }
        qw.eq("district_id", 1319);
        villages = townsService.list(qw);
        Map<String,Object> map = new HashMap<>();
        map.put("villages",villages);
        return R.ok(map);
    }

    /**
     * 重置二维码
     */
    @Log("重置二维码")
    @PostMapping("/resetQrCode")
    @ResponseBody
    @RequiresPermissions("module:citizen:edit")
    public R resetQrcode(Integer id) {
        Citizen citizen = citizenService.findById(id);
        if(citizen != null){
            try{
                String villageName = citizen.getVillageName();
                if(StrUtil.isEmpty(villageName)){
                    Towns village = townsService.findById(citizen.getVillageId());
                    if(village!=null){
                        villageName = village.getTownName();
                    }
                }

                String townName = citizen.getTownName();
                if(StrUtil.isEmpty(townName)){
                    Towns town = townsService.findById(citizen.getTownId());
                    if(town!=null){
                        townName = town.getTownName();
                    }
                }


                String qrCode = "";
                String fileName = citizen.getRoomNo() + " " +citizen.getHolderName() +".jpg";
                String content = "{\"qrtype\":\"room\",\"room_id\":" + citizen.getId() + ",\"town_name\":\"" + townName + "\",\"village_name\":\"" + villageName + "\"}";
                Aes aes = new Aes();
                content = aes.encrypt(content);
                System.out.println("content:  "+ content);
                //上传头像到OSS
                String img_key = "";
                img_key = OssUtil.getUploadPrefix(OssUtil.TYPE_ROOM_PHOTOS) + citizen.getTownId() + "/"  + fileName;
                QRCodeUtilEx.createQrCodeImg(content, citizen.getRoomNo() + " " + citizen.getHolderName(), null,
                        uploadPath +"/"+ img_key, true);
                qrCode = img_key;
                citizen.setQrCode(qrCode);
            }catch (Exception ex){
                ex.printStackTrace();
            }
            if (citizenService.updateById(citizen)) {
                return R.ok();
            }
        }
        return R.error();
    }

    /**
     * 通用下载请求
     * @param townId 乡镇id
     * @param beginDate
     * @param endDate
     * @param response
     * @param request
     */
    @GetMapping("/downloadQRCode")
    @RequiresPermissions("module:citizen:download")
    public void fileDownload(Integer townId, Integer villageId ,String beginDate, String endDate, HttpServletResponse response, HttpServletRequest request) {
        QueryWrapper<Citizen> qw = new QueryWrapper<>();
        if(townId != null){
            qw.eq("town_id", townId);
        }

        if(villageId != null){
            qw.eq("village_id", villageId);
        }
        if(StrUtil.isNotEmpty(beginDate) && StrUtil.isNotEmpty(endDate)){
            qw.between("update_time",beginDate + " 00:00:00", endDate + " 23:59:59");
        }

        List<Citizen> citizens = citizenService.list(qw);
        String outputFileName = System.currentTimeMillis() + "_共" + citizens.size() + ".zip";
        try {
            // 设置response参数
            response.reset();
            response.setContentType("content-type:octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((outputFileName).getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            ZipArchiveOutputStream zous = new ZipArchiveOutputStream(out);
            zous.setUseZip64(Zip64Mode.AsNeeded);
            List<File> fileList = new ArrayList<>();
            for (Citizen citizen : citizens) {
                fileList.add(new File(uploadPath + "/room/"+ townId +"/" + citizen.getRoomNo() + " " + citizen.getHolderName()  +".jpg"));
            }
            for (File file : fileList) {
                String file1 = file.getName();
                InputStream inputStream = new FileInputStream(file);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                if (baos != null) {
                    baos.flush();
                }
                byte[] bytes = baos.toByteArray();
                //设置文件名
                ArchiveEntry entry = new ZipArchiveEntry(file1);
                zous.putArchiveEntry(entry);
                zous.write(bytes);
                zous.closeArchiveEntry();
                if (baos != null) {
                    baos.close();
                }
            }
            if (zous != null) {
                zous.close();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Log("批量新增居民信息页面")
    @GetMapping("/goBatchAdd")
    String goBatchAdd() {
        return "module/citizen/upload";
    }


    @Log("批量新增居民信息页面")
    @GetMapping("/goBatchAddBaoBao")
    String goBatchAddBaoBao() {
        return "module/citizen/upload";
    }

    @Log("批量新增居民信息页面")
    @GetMapping("/goBatchAddAdmin")
    String goBatchAddAdmin() {
        return "system/user/upload_baobao";
    }

    /**
     *  批量导入居民信息
     * @param file
     */
    @RequestMapping(value = "/excelBatch", method = RequestMethod.POST)
    @ResponseBody
    Object excelBatch(@RequestParam(value="file", required = false) MultipartFile file){
        long t1 = System.currentTimeMillis();
        List<CitizenExcel> list = ExcelUtils.readExcel("", CitizenExcel.class, file);
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("read over! cost:%sms", (t2 - t1)));
        list.forEach(b -> {
            if(StrUtil.isNotEmpty(b.getHolderName())){
                String townName = "", villageName = "";
                QueryWrapper<Towns> qwTown = new QueryWrapper<>();
                qwTown.eq("grid_level", 2);
                qwTown.eq("parent_id", 0);
                qwTown.eq("town_name", StringUtil.replaceBlankSpace(b.getTownName()));
                qwTown.last("limit 1");
                Towns town = townsService.getOne(qwTown);
                if(town != null){
                    townName = town.getTownName();

                    QueryWrapper<Towns> qwVillage = new QueryWrapper<>();
                    qwVillage.eq("parent_id", town.getId());
                    qwVillage.eq("grid_level", 3);
                    qwVillage.and(wrapper->{
                        wrapper.like("town_name",
                                StringUtil.replaceBlankSpace(
                                        b.getVillageName()).replace("村委会","")
                                        .replace("村",""));
                    });
                    qwVillage.last("limit 1");
                    Towns village = townsService.getOne(qwVillage);
                    if(village != null){
//                    village = new Towns();
//                    village.setParentId(town.getId());
//                    village.setTownName(StringUtil.replaceBlankSpace(b.getVillageName()).replace("村委会","").replace("村",""));
//                    villageName = b.getTownName().trim().replace("村委会","").replace("村","");
//                    village.setState(1);
//                    village.setGridLevel(3);
//                    village.setDelFlag(0);
//                    townsService.save(village);

                        villageName = village.getTownName();

                        QueryWrapper<Citizen> qw = new QueryWrapper<>();
                        qw.eq("town_id", town.getId());
                        qw.eq("village_id", village.getId());
                        qw.eq("room_no", b.getRoomNo().replace(" ",""));
                        qw.eq("holder_name", b.getHolderName().replace(" ",""));
                        qw.last("limit 1");
                        System.out.println("户主姓名：" + b.getHolderName());
                        boolean blExist = true;
                        Citizen citizen = citizenService.getOne(qw);
                        if (citizen == null) {
                            citizen = new Citizen();
                            citizen.setState(1);
                            citizen.setCreateTime(new Date());
                            citizen.setUpdateTime(new Date());
                            citizen.setHolderName(StringUtil.replaceBlankSpace(b.getHolderName()));
                            citizen.setTownId(town.getId());
                            citizen.setTownName(town.getTownName());
                            citizen.setVillageId(village.getId());
                            citizen.setVillageName(village.getTownName());
                            citizen.setRoomNo(StringUtil.replaceBlankSpace(b.getRoomNo()));
                            citizen.setRoomType(2);
                            citizen.setHeatingMode(3);
                            int starLevel = 0;//
                            if(StrUtil.isNotEmpty(b.getStarLevel())){
                                starLevel = Integer.parseInt(b.getStarLevel().replace("级",""));
                            }
                            citizen.setStarLevel(starLevel);
                            citizen.setRemark(b.getRemark());
                            blExist = false;
                        }
                        if(!blExist){
                            citizenService.save(citizen);
                        }else{
                            int importCount = citizen.getImportCount();
                            citizen.setImportCount(importCount + 1);
                            citizen.setUpdateTime(new Date());
                            citizenService.updateById(citizen);
                        }

                        if (!blExist || StrUtil.isEmpty(citizen.getQrCode())) {
//                    try {
//                        String qrCode = "";
//                        String fileName = citizen.getRoomNo() + " " +  citizen.getHolderName()  +".jpg";
//                        String content = "{\"qrtype\":\"room\",\"room_id\":" + citizen.getId() + ",\"town_name\":\"" + townName + "\",\"village_name\":\"" + villageName + "\"}";
//                        Aes aes = new Aes();
//                        content = aes.encrypt(content);
//                        System.out.println("content:  "+ content);
//                        //上传头像到OSS
//                        String img_key = "";
//                        img_key = OssUtil.getUploadPrefix(OssUtil.TYPE_ROOM_PHOTOS) + town.getId() + "/" + fileName;
//                        QRCodeUtilEx.createQrCodeImg(content, citizen.getRoomNo()+ " " + citizen.getHolderName(), null,
//                                uploadPath +"/"+ img_key, true);
//                        qrCode = img_key;
//                        citizen.setQrCode(qrCode);
//                        citizenService.updateById(citizen);
//                    } catch (Exception ex) {
//                        ex.printStackTrace();
//                    }
                        }
                        try {
                            String qrCode = "";
                            String fileName = citizen.getRoomNo() + " " +  citizen.getHolderName()  +".jpg";
                            String content = "{\"qrtype\":\"room\",\"room_id\":" + citizen.getId() + ",\"town_name\":\"" + townName + "\",\"village_name\":\"" + villageName + "\"}";
                            Aes aes = new Aes();
                            content = aes.encrypt(content);
                            System.out.println("content:  "+ content);
                            //上传头像到OSS
                            String img_key = "";
                            img_key = OssUtil.getUploadPrefix(OssUtil.TYPE_ROOM_PHOTOS) + town.getId() + "/" + fileName;
                            QRCodeUtilEx.createQrCodeImg(content, citizen.getRoomNo()+ " " + citizen.getHolderName(), null,
                                    uploadPath +"/"+ img_key, true);
                            qrCode = img_key;
                            citizen.setQrCode(qrCode);
                            citizenService.updateById(citizen);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                        if(citizen != null){
                            if(StrUtil.isNotEmpty(b.getBaoBaoName())){
                                String baobaoName = b.getBaoBaoName().replace("、",",").replace("，",",");
                                String[] baobaoNames = baobaoName.split(",");
                                for (String name : baobaoNames){
                                    //包保排查人员
                                    QueryWrapper<UserDO> qwUser = new QueryWrapper<>();
                                    qwUser.eq("town_id",town.getId());
                                    qwUser.eq("name",name);
                                    qwUser.last("limit 1");
                                    UserDO userDO = userService.getOne(qwUser);
                                    if(userDO == null){
                                        userDO = new UserDO();
                                        userDO.setTownId(town.getId());
                                        userDO.setTownName(town.getTownName());
                                        userDO.setVillageId(village.getId());
                                        userDO.setVillageName(village.getTownName());
                                        userDO.setRoleId(8);
                                        userDO.setUserType(7);
                                        userDO.setName(name);
                                        userDO.setGmtCreate(new Date());
                                        userDO.setStatus(1);
                                        userDO.setIsSendMsg(0);
                                        userDO.setUserLevel(3);
                                        userService.save(userDO);
                                    }

                                    citizen.setManagerName(b.getBaoBaoName());
                                    citizen.setManagerSysUserId(userDO.getUserId());

                                    QueryWrapper<SysUserTownRelation> qwRelation = new QueryWrapper<>();
                                    qwRelation.eq("town_id",town.getId());
                                    qwRelation.eq("village_id",village.getId());
                                    qwRelation.eq("sys_user_id",userDO.getUserId());
                                    qwRelation.eq("check_type", 0);
                                    qwRelation.last("limit 1");
                                    SysUserTownRelation userTownRelation = userTownRelationService.getOne(qwRelation);
                                    if(userTownRelation == null){
                                        userTownRelation = new SysUserTownRelation();
                                        userTownRelation.setName(name);
                                        userTownRelation.setSysUserId(userDO.getUserId());
                                        userTownRelation.setTownId(town.getId());
                                        userTownRelation.setTownName(town.getTownName());
                                        userTownRelation.setVillageId(village.getId());
                                        userTownRelation.setVillageName(village.getTownName());
                                        userTownRelation.setCreateTime(new Date());
                                        userTownRelation.setState(1);
                                        userTownRelation.setCheckType(0);
                                        userTownRelationService.save(userTownRelation);
                                    }
                                }
                            }

                            if(StrUtil.isNotEmpty(b.getDuDaoName())){
                                String dudaoName = b.getDuDaoName().replace("、",",");
                                String[] dudaoNames = dudaoName.split(",");
                                for (String name : dudaoNames){
                                    //包保排查人员
                                    QueryWrapper<UserDO> qwUserDirect = new QueryWrapper<>();
                                    qwUserDirect.eq("town_id",town.getId());
                                    qwUserDirect.eq("name",name);
                                    qwUserDirect.last("limit 1");
                                    UserDO userDODirect = userService.getOne(qwUserDirect);
                                    if(userDODirect == null){
                                        userDODirect = new UserDO();
                                        userDODirect.setTownId(town.getId());
                                        userDODirect.setTownName(town.getTownName());
                                        userDODirect.setVillageId(village.getId());
                                        userDODirect.setVillageName(village.getTownName());
                                        userDODirect.setRoleId(9);
                                        userDODirect.setUserType(7);
                                        userDODirect.setName(name);
                                        userDODirect.setGmtCreate(new Date());
                                        userDODirect.setStatus(1);
                                        userDODirect.setIsSendMsg(0);
                                        userDODirect.setUserLevel(3);
                                        userService.save(userDODirect);
                                    }

                                    citizen.setDirectManagerName(b.getDuDaoName());
                                    citizen.setDirectManagerSysUserId(userDODirect.getUserId());
                                    citizenService.updateById(citizen);


                                    QueryWrapper<SysUserTownRelation> qwRelation1 = new QueryWrapper<>();
                                    qwRelation1.eq("town_id",town.getId());
                                    qwRelation1.eq("village_id",village.getId());
                                    qwRelation1.eq("sys_user_id",userDODirect.getUserId());
                                    qwRelation1.eq("check_type", 1);
                                    qwRelation1.last("limit 1");
                                    SysUserTownRelation userTownRelation1 = userTownRelationService.getOne(qwRelation1);
                                    if(userTownRelation1 == null){
                                        userTownRelation1 = new SysUserTownRelation();
                                        userTownRelation1.setName(name);
                                        userTownRelation1.setSysUserId(userDODirect.getUserId());
                                        userTownRelation1.setTownId(town.getId());
                                        userTownRelation1.setTownName(town.getTownName());
                                        userTownRelation1.setVillageId(village.getId());
                                        userTownRelation1.setVillageName(village.getTownName());
                                        userTownRelation1.setCreateTime(new Date());
                                        userTownRelation1.setState(1);
                                        userTownRelation1.setCheckType(1);
                                        userTownRelationService.save(userTownRelation1);
                                    }
                                }
                            }

                        }
                    }
                    else{
                        System.out.println("村名：" + b.getVillageName() + " 不存在");
                    }
                }
            }
        });
        return R.ok();
    }

    /**
     *  批量导入设备保养点
     * @param file
     */
    @RequestMapping(value = "/excelBatchSysUser", method = RequestMethod.POST)
    @ResponseBody
    Object excelBatchSysUser(@RequestParam(value="file", required = false) MultipartFile file){
        long t1 = System.currentTimeMillis();
        List<AdminSysUserExcel> list = ExcelUtils.readExcel("", AdminSysUserExcel.class, file);
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("read over! cost:%sms", (t2 - t1)));
        list.forEach(b -> {
            RoleDO roleDO = roleService.selectByUniqueColumn("role_name",StringUtil.replaceBlankSpace(b.getRoleName()));
            if(roleDO!=null){
                QueryWrapper<Towns> qwTown = new QueryWrapper<>();
                qwTown.eq("grid_level", 2);
                qwTown.eq("parent_id", 0);
                qwTown.like("town_name", StringUtil.replaceBlankSpace(b.getTownName()));
                Towns town = townsService.getOne(qwTown);
                if(town != null){
                    Towns village = null;
                    if(StrUtil.isNotEmpty(b.getVillageName())){
                        QueryWrapper<Towns> qwVillage = new QueryWrapper<>();
                        qwVillage.eq("parent_id", town.getId());
                        qwVillage.eq("grid_level", 3);
                        qwVillage.like("town_name",
                                StringUtil.replaceBlankSpace(
                                        b.getVillageName()).replace("村委会","")
                                        .replace("村",""));
                        village = townsService.getOne(qwVillage);
                        if(village != null){
                            QueryWrapper<UserDO> qw= new QueryWrapper<>();
                            qw.eq("town_name",StringUtil.replaceBlankSpace(b.getTownName()));
                            qw.eq("name",StringUtil.replaceBlankSpace(b.getRealName()));
                            UserDO userDO = userService.getOne(qw);
                            if(userDO == null){
                                userDO = new UserDO();
                                userDO.setGroupId(0);
                                userDO.setUsername(StringUtil.replaceBlankSpace(b.getPhoneNum()));
                                userDO.setUserType(roleDO.getUserType());
                                userDO.setRoleId(roleDO.getRoleId());
                                userDO.setPassword(MD5Utils.encrypt(StringUtil.replaceBlankSpace(userDO.getUsername()), "123456"));
                                userDO.setMobile(StringUtil.replaceBlankSpace(b.getPhoneNum()));
                                userDO.setName(StringUtil.replaceBlankSpace(b.getRealName()));
                                userDO.setTownName(StringUtil.replaceBlankSpace(b.getTownName()));
                                if(town != null){
                                    userDO.setTownId(town.getId());
                                }
                                if(StrUtil.isNotEmpty(StringUtil.replaceBlankSpace(b.getVillageName()))){
                                    userDO.setVillageName(StringUtil.replaceBlankSpace(b.getVillageName()));
                                }
                                if(village!=null){
                                    userDO.setVillageId(village.getId());
                                }else{
                                    userDO.setVillageId(0);
                                }

                                userDO.setStatus(1);
                                userDO.setShopId(0);
                                if(b.getQxName().equals("县级")){
                                    userDO.setUserLevel(1);
                                } else if(b.getQxName().equals("镇级")){
                                    userDO.setUserLevel(2);
                                } else if(b.getQxName().equals("村级")){
                                    userDO.setUserLevel(3);
                                }
                                userService.save(userDO);
                            }else{
                                userDO.setTownName(StringUtil.replaceBlankSpace(b.getTownName()));
                                if(town != null){
                                    userDO.setTownId(town.getId());
                                }
                                if(StrUtil.isNotEmpty(StringUtil.replaceBlankSpace(b.getVillageName()))){
                                    userDO.setVillageName(StringUtil.replaceBlankSpace(b.getVillageName()));
                                }
                                if(village != null){
                                    userDO.setVillageId(village.getId());
                                }else{
                                    userDO.setVillageId(0);
                                }
                                if(b.getQxName().equals("县级")){
                                    userDO.setUserLevel(1);
                                } else if(b.getQxName().equals("镇级")){
                                    userDO.setUserLevel(2);
                                } else if(b.getQxName().equals("村级")){
                                    userDO.setUserLevel(3);
                                }
                                userService.updateById(userDO);
                            }

                            QueryWrapper<SysUserTownRelation> qwRelation = new QueryWrapper<>();
                            qwRelation.eq("sys_user_id",userDO.getUserId());
                            qwRelation.eq("name",b.getRealName());
                            if(roleDO.getRoleId() == 8){
                                qwRelation.eq("check_type", 0);
                            }else{
                                qwRelation.eq("check_type", 1);
                            }
                            qwRelation.last("limit 1");
                            SysUserTownRelation userTownRelation = userTownRelationService.getOne(qwRelation);
                            if(userTownRelation == null){
                                userTownRelation = new SysUserTownRelation();
                                userTownRelation.setName(StringUtil.replaceBlankSpace(b.getRealName()));
                                userTownRelation.setTownName(town.getTownName());
                                userTownRelation.setTownId(town.getId());
                                if(village != null){
                                    userTownRelation.setVillageName(village.getTownName());
                                    userTownRelation.setVillageId(village.getId());
                                }
                                userTownRelation.setSysUserId(userDO.getUserId());
                                userTownRelation.setCreateTime(new Date());
                                userTownRelation.setState(1);
                                if(roleDO.getRoleId() == 8) {
                                    userTownRelation.setCheckType(0);
                                }else{
                                    userTownRelation.setCheckType(1);
                                }
                                userTownRelationService.save(userTownRelation);
                            }else{
                                userTownRelation.setTownName(town.getTownName());
                                userTownRelation.setTownId(town.getId());
                                if(village!=null){
                                    userTownRelation.setVillageName(village.getTownName());
                                    userTownRelation.setVillageId(village.getId());
                                }
                                if(roleDO.getRoleId() == 8) {
                                    userTownRelation.setCheckType(0);
                                }else{
                                    userTownRelation.setCheckType(1);
                                }
                                userTownRelationService.updateById(userTownRelation);
                            }
                        }
                    }

                }
            }
        });
        return R.ok();
    }

    /**
     *  批量导入设备保养点
     * @param file
     */
    @RequestMapping(value = "/excelBatchBaoBao", method = RequestMethod.POST)
    @ResponseBody
    Object excelBatchBaoBao(@RequestParam(value="file", required = false) MultipartFile file){
        long t1 = System.currentTimeMillis();
        List<CitizenExcel> list = ExcelUtils.readExcel("", CitizenExcel.class, file);
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("read over! cost:%sms", (t2 - t1)));
        list.forEach(b -> {
            QueryWrapper<Towns> qwTown = new QueryWrapper<>();
            qwTown.eq("grid_level", 2);
            qwTown.eq("parent_id", 0);
            qwTown.eq("town_name", b.getTownName().trim());
            qwTown.last("limit 1");
            Towns town = townsService.getOne(qwTown);
            if(town != null){
                QueryWrapper<Towns> qwVillage = new QueryWrapper<>();
                qwVillage.eq("parent_id", town.getId());
                qwVillage.eq("grid_level", 3);
                qwVillage.like("town_name",
                        StringUtil.replaceBlankSpace(
                                b.getVillageName()).replace("村委会","")
                                .replace("村",""));
                qwVillage.last("limit 1");
                Towns village = townsService.getOne(qwVillage);
                if(village != null){
                    QueryWrapper<Citizen> qw = new QueryWrapper<>();
                    qw.eq("town_id", town.getId());
                    qw.eq("village_id", village.getId());
                    qw.eq("room_no", b.getRoomNo());
                    qw.eq("holder_name", b.getHolderName());
                    qw.last("limit 1");
                    Citizen citizen = citizenService.getOne(qw);
                    if(citizen != null){
                        if(StrUtil.isNotEmpty(b.getBaoBaoName())){
                            String baobaoName = b.getBaoBaoName().replace("、",",").replace("，",",");
                            String[] baobaoNames = baobaoName.split(",");
                            for (String name : baobaoNames){
                                //包保排查人员
                                QueryWrapper<UserDO> qwUser = new QueryWrapper<>();
                                qwUser.eq("town_id",town.getId());
                                qwUser.eq("name",name);
                                qwUser.last("limit 1");
                                UserDO userDO = userService.getOne(qwUser);
                                if(userDO == null){
                                    userDO = new UserDO();
                                    userDO.setTownId(town.getId());
                                    userDO.setTownName(town.getTownName());
                                    userDO.setVillageId(village.getId());
                                    userDO.setVillageName(village.getTownName());
                                    userDO.setRoleId(8);
                                    userDO.setUserType(7);
                                    userDO.setName(name);
                                    userDO.setGmtCreate(new Date());
                                    userDO.setStatus(1);
                                    userDO.setIsSendMsg(0);
                                    userDO.setUserLevel(3);
                                    userService.save(userDO);
                                }

                                QueryWrapper<SysUserTownRelation> qwRelation = new QueryWrapper<>();
                                qwRelation.eq("town_id",town.getId());
                                qwRelation.eq("village_id",village.getId());
                                qwRelation.eq("sys_user_id",userDO.getUserId());
                                qwRelation.eq("check_type", 0);
                                qwRelation.last("limit 1");
                                SysUserTownRelation userTownRelation = userTownRelationService.getOne(qwRelation);
                                if(userTownRelation == null){
                                    userTownRelation = new SysUserTownRelation();
                                    userTownRelation.setName(name);
                                    userTownRelation.setSysUserId(userDO.getUserId());
                                    userTownRelation.setTownId(town.getId());
                                    userTownRelation.setTownName(town.getTownName());
                                    userTownRelation.setVillageId(village.getId());
                                    userTownRelation.setVillageName(village.getTownName());
                                    userTownRelation.setCreateTime(new Date());
                                    userTownRelation.setState(1);
                                    userTownRelation.setCheckType(0);
                                    userTownRelationService.save(userTownRelation);
                                }
                            }
                        }

                        if(StrUtil.isNotEmpty(b.getDuDaoName())){
                            String dudaoName = b.getDuDaoName().replace("、",",");
                            String[] dudaoNames = dudaoName.split(",");
                            for (String name : dudaoNames){
                                //包保排查人员
                                QueryWrapper<UserDO> qwUserDirect = new QueryWrapper<>();
                                qwUserDirect.eq("town_id",town.getId());
                                qwUserDirect.eq("name",name);
                                qwUserDirect.last("limit 1");
                                UserDO userDODirect = userService.getOne(qwUserDirect);
                                if(userDODirect == null){
                                    userDODirect = new UserDO();
                                    userDODirect.setTownId(town.getId());
                                    userDODirect.setTownName(town.getTownName());
                                    userDODirect.setVillageId(village.getId());
                                    userDODirect.setVillageName(village.getTownName());
                                    userDODirect.setRoleId(8);
                                    userDODirect.setUserType(7);
                                    userDODirect.setName(name);
                                    userDODirect.setGmtCreate(new Date());
                                    userDODirect.setStatus(1);
                                    userDODirect.setIsSendMsg(0);
                                    userDODirect.setUserLevel(3);
                                    userService.save(userDODirect);
                                }

                                QueryWrapper<SysUserTownRelation> qwRelation1 = new QueryWrapper<>();
                                qwRelation1.eq("town_id",town.getId());
                                qwRelation1.eq("village_id",village.getId());
                                qwRelation1.eq("sys_user_id",userDODirect.getUserId());
                                qwRelation1.eq("check_type", 1);
                                qwRelation1.last("limit 1");
                                SysUserTownRelation userTownRelation1 = userTownRelationService.getOne(qwRelation1);
                                if(userTownRelation1 == null){
                                    userTownRelation1 = new SysUserTownRelation();
                                    userTownRelation1.setName(name);
                                    userTownRelation1.setSysUserId(userDODirect.getUserId());
                                    userTownRelation1.setTownId(town.getId());
                                    userTownRelation1.setTownName(town.getTownName());
                                    userTownRelation1.setVillageId(village.getId());
                                    userTownRelation1.setVillageName(village.getTownName());
                                    userTownRelation1.setCreateTime(new Date());
                                    userTownRelation1.setState(1);
                                    userTownRelation1.setCheckType(1);
                                    userTownRelationService.save(userTownRelation1);
                                }
                            }
                        }

                    }
                }
            }
        });
        return R.ok();
    }


    /**
     * 下载二维码
     */
    @Log("下载二维码")
    @GetMapping("/download/{roomId}")
    public void download(@PathVariable("roomId") Integer roomId, HttpServletResponse response) {
        Citizen citizen = citizenService.findById(roomId);
        if(citizen!=null){
            FileUtils.download(uploadPath + citizen.getQrCode(),response);
        }
    }


    @RequiresPermissions("module:citizen:qrcode")
    @Log("批量生成二维码")
    @PostMapping("/batchQrCode")
    @ResponseBody
    R batchQrcode(@RequestParam("ids[]") Integer[] citizenIds) {
        int count = 0;
        for (Integer id : citizenIds){
            Citizen citizen = citizenService.findById(id);
            if(citizen != null){
                try{
                    String villageName = citizen.getVillageName();
                    if(StrUtil.isEmpty(villageName)){
                        Towns village = townsService.findById(citizen.getVillageId());
                        if(village!=null){
                            villageName = village.getTownName();
                        }
                    }


                    String townName = citizen.getTownName();
                    if(StrUtil.isEmpty(townName)){
                        Towns town = townsService.findById(citizen.getTownId());
                        if(town!=null){
                            townName = town.getTownName();
                        }
                    }

                    String qrCode = "";
                    String fileName = citizen.getRoomNo() +" "+ citizen.getHolderName()  +".jpg";

                    String content = "{\"qrtype\":\"room\",\"room_id\":" + citizen.getId() + ",\"town_name\":\"" + townName + "\",\"village_name\":\""+villageName+"\"}";
                    Aes aes = new Aes();
                    content = aes.encrypt(content);
                    System.out.println("content:  "+ content);
                    //上传头像到OSS
                    String img_key = "";
                    img_key = OssUtil.getUploadPrefix(OssUtil.TYPE_ROOM_PHOTOS) + citizen.getTownId() + "/" + fileName;
                    QRCodeUtilEx.createQrCodeImg(content, citizen.getRoomNo()+ " " + citizen.getHolderName(), null,
                            uploadPath +"/"+ img_key, true);
                    qrCode = img_key;
                    citizen.setQrCode(qrCode);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
                if (citizenService.updateById(citizen)) {
                    count ++;
                }
            }
        }
        return R.ok("共成功"+count+"个");
    }


    @Log("导出列表")
    @GetMapping("/exportExcel")
    public void testExportExcel(@RequestParam("townId") String townId,
                                @RequestParam("villageId") String villageId, HttpServletResponse response){
//        UserDO user = getUser();
        Map<String,Object> map = new HashMap<>();
        map.put("town_id", townId);
        if(StrUtil.isNotEmpty(villageId)){
            map.put("village_id", villageId);
        }
        List<Citizen> records = citizenService.selectByMap(map);
        ExcelUtils.writeExcel(response, records, Citizen.class, System.currentTimeMillis() + "_居民信息.xlsx");
    }



    /**
     * 保存
     */
    @Log("新增设备")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:citizen:add")
    public R save(@Valid Citizen citizen) {
        try{
            boolean bl = citizenService.save(citizen);
            if(bl){
                String villageName = "";
                Towns village = townsService.findById(citizen.getVillageId());
                if(village!=null){
                    villageName = village.getTownName();
                }
                citizen.setVillageName(villageName);

                String townName = "";
                Towns town = townsService.findById(citizen.getTownId());
                if(town!=null){
                    townName = town.getTownName();
                }
                citizen.setTownName(townName);

                String qrCode = "";
                String fileName = citizen.getRoomNo() + " " + citizen.getHolderName() +".jpg";

                String content = "{\"qrtype\":\"room\",\"room_id\":" + citizen.getId() + ",\"town_name\":\"" + townName + "\",\"village_name\":\""+villageName+"\"}";
                Aes aes = new Aes();
                content = aes.encrypt(content);
                System.out.println("content:  "+ content);
                //上传头像到OSS
                String img_key = "";
                img_key = OssUtil.getUploadPrefix(OssUtil.TYPE_ROOM_PHOTOS) + citizen.getTownId() + "/" + fileName;
                QRCodeUtilEx.createQrCodeImg(content, citizen.getRoomNo()+ " " + citizen.getHolderName(), null,
                        uploadPath +"/"+ img_key, true);
                qrCode = img_key;
                citizen.setQrCode(qrCode);
                bl = citizenService.updateById(citizen);
                if (bl) {
                    return R.ok();
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @Log("更新设备")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:citizen:edit")
    public R update(@Valid Citizen citizen) {

        String villageName = "";
        Towns village = townsService.findById(citizen.getVillageId());
        if(village!=null){
            villageName = village.getTownName();
            citizen.setVillageName(villageName);
        }

        String townName = "";
        Towns town = townsService.findById(citizen.getTownId());
        if(town!=null){
            townName = town.getTownName();
            citizen.setTownName(townName);
        }
        citizen.setQrCode("room/"+citizen.getTownId()+"/" + citizen.getRoomNo()  + " "+ citizen.getHolderName()  + ".jpg");
        citizenService.updateById(citizen);
        return R.ok();
    }


    /**
     * 修改
     */
    @Log("更新设备")
    @ResponseBody
    @PostMapping("/updateQrCode/{townId}")
    public R updateQrCode(@PathVariable("townId") Integer townId) {
        if(townId == null){
            return R.error("请选择乡镇");
        }
        List<Citizen> list = citizenService.selectListByColumn("town_id",townId);
        if(CollUtil.isNotEmpty(list)){
            for (Citizen citizen : list){
                String villageName = "";
                Towns village = townsService.findById(citizen.getVillageId());
                if(village!=null){
                    villageName = village.getTownName();
                }

                String townName = "";
                Towns town = townsService.findById(citizen.getTownId());
                if(town!=null){
                    townName = town.getTownName();
                }

                String qrCode = "";
                String fileName = citizen.getRoomNo() + " " + citizen.getHolderName()  +".jpg";

                String content = "{\"qrtype\":\"room\",\"room_id\":" + citizen.getId() + ",\"town_name\":\""
                        + townName + "\",\"village_name\":\""+villageName+"\"}";
                Aes aes = new Aes();
                content = aes.encrypt(content);
                System.out.println("content:  "+ content);
                //上传头像到OSS
                String img_key = "";
                img_key = OssUtil.getUploadPrefix(OssUtil.TYPE_ROOM_PHOTOS) + townId + "/"  + fileName;

                try{
                    QRCodeUtilEx.createQrCodeImg(content, citizen.getRoomNo()+ " " + citizen.getHolderName(), null,
                            uploadPath +"/"+ img_key, true);
                }catch (Exception e){

                }

                qrCode = img_key;
                citizen.setQrCode(qrCode);
                citizenService.updateById(citizen);
            }
        }
        return R.ok();
    }


    /**
     * 删除
     */
    @Log("删除设备")
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions("module:citizen:remove")
    public R remove( Integer id) {
        if (citizenService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }
}
